import axios from 'axios'
import * as TYPES from "../constants/actions"
import store from '../store'

let isDev = (process.env.NODE_ENV === 'development')
console.log('当前的环境配置是', isDev ? '开发环境' : '生产环境')
axios.defaults.globalStyle = 0

// axios.defaults.baseURL = 'http://121.42.252.26/autoreport';
// axios.defaults.baseURL = isDev ? 'http://121.42.252.26/autoreport' : '/autoreport';
axios.defaults.baseURL = isDev ? 'http://121.42.187.170/autoreport' : '/autoreport';
// let style = null


//request cancel loading
axios.interceptors.request.use(function (config) {
  // Do something before request is sent
  store.dispatch({
    type:"REQUEST_BEGIN"
  })
  return config;
}, function (error) {
  return Promise.reject(error);
});

//response reacord loading
axios.interceptors.response.use(function (config) {
  // Do something before request is sent
  store.dispatch({
    type:"REQUEST_COMPLETE"
  })
  if(!config.data.success){
    store.dispatch({
      type:"ERROR_OCCUR",
      payload:"数据获取失败!"
    })
  }
  axios.defaults.globalStyle = config.config.params.style
  return config;
}, function (error) {
  let errorDetail = error.response.data
  store.dispatch({
    type:"REQUEST_COMPLETE"
  })
  store.dispatch({
    type:"ERROR_OCCUR",
    payload:"请求发生了错误!"
  })


});


export default {
  [TYPES.GET_TEMPLATES]: (params) => {
    return {
      type: TYPES.GET_TEMPLATES,
      payload: axios.get('/template/config',{params})
    }
  },
  [TYPES.GET_MODULE_DATA]: (params) => {
    return {
      type: TYPES.GET_MODULE_DATA,
      payload: axios.get('/select',{params})
    }
  },
  [TYPES.SYNC_MODULES_IN_TEMPLATES]: (params, hosId) => {
    return {
      type: TYPES.SYNC_MODULES_IN_TEMPLATES,
      payload: axios.post(`/template/update?hosId=${hosId}`,{params})
    }
  },
  [TYPES.GET_MODULE_DETAIL]: (params) => ({
    type: TYPES.GET_MODULE_DETAIL,
    payload: axios.get('/module',{params})
  }),
  [TYPES.SAVE_TEXTAREA]: (params) => ({
    type: TYPES.SAVE_TEXTAREA,
    payload: params
  }),
  [TYPES.SAVE_DATAAREA]: (params) => {
    return {
      type: TYPES.SAVE_DATAAREA,
      globalStyle: axios.defaults.globalStyle,
      payload: params
    }
  },
  [TYPES.SYNC_TEXTAREA]: (params) => ({
    type: TYPES.SYNC_TEXTAREA,
    payload: axios.post('/module/update',params)
  }),
  [TYPES.SYNC_DATAAREA]: (params) => ({
    type: TYPES.SYNC_DATAAREA,
    payload: axios.get('/updateChart',{params})
  }),
  [TYPES.ADD_NEW_MODULE]: (params) => ({
    type: TYPES.ADD_NEW_MODULE,
    payload: axios.post('/module/insert',params)
  }),
  [TYPES.CLEAR_DAYA]: (params) => {
    return {
      type: TYPES.CLEAR_DAYA,
      payload: axios.get('/deleteChart',{params})
    }
  },
  [TYPES.CHECK_CHART]: (params) => {
    return {
      type: TYPES.CHECK_CHART,
      payload: axios.get('/checkChart',{params})
    }
  }
}

